﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage;
using Windows.Storage.Pickers;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;


// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace StudyTime_1
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class quizMe : StudyTime_1.Common.LayoutAwarePage
    {

        public List<quizQuest> quizList = new List<quizQuest>();
      //  public List<reviewClass> reviewList = new List<reviewClass>();
        private StorageFile storage;

        //string[,] questAnswer = new string[500, 2];
        //int convLength;
        int currPage = 0;

        int scoreCount = 0;

        bool listCreated = false;
        private string fileName;
        private string filePath;

        private string actualAnswerText;
        private string userAnswerText;

        Uri blankURI = new Uri("",UriKind.Relative);



        public quizMe()
        {
            this.InitializeComponent();

            answer.ItemsSource = new List<string> { "A", "B", "C", "D" };
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        async private void loadData(List<quizQuest> quiz)
        {

            //convLength = 0;
            
            quizList.Clear();
            currPage = 0;
            {

                StorageFolder storageFolder = KnownFolders.VideosLibrary;
                


                {
                    try
                    {
                        questions.Text = fileName;
                        //Opens the text file that the array is stored in.
                        // storage = await storageFolder.GetFileAsync(filePath);




                        DataContractSerializer serializer = new DataContractSerializer(typeof(List<quizQuest>));

                        var file = await storage.OpenAsync(FileAccessMode.Read);
                        Stream inStream = file.AsStreamForRead();

                        quiz = serializer.ReadObject(inStream) as List<quizQuest>;

                        foreach (quizQuest quizQuest in quiz)
                        {
                            quizList.Add(quizQuest);
                        }


                        //questions.Text = quizList[0].question.ToString();
                        questions.Text = quizList[currPage].question.ToString() + Environment.NewLine + "A: " + quizList[0].answerA + Environment.NewLine + "B: " +
                    quizList[0].answerB + Environment.NewLine + "C: " + quizList[0].answerC +
                    Environment.NewLine + "D: " + quizList[0].answerD;

                        if (quizList[0].picture != null)
                        {
                            setImage(currPage, false);
                        }

                        listCreated = true;

                    }
                    catch (IOException)
                    {

                    }
                }
            }
        }

        private void back_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.GoBack();
        }

        async private void selection_Click(object sender, RoutedEventArgs e)
        {
            {
                {

                    FileOpenPicker openPicker = new FileOpenPicker();
                    openPicker.ViewMode = PickerViewMode.List;
                    openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
                    openPicker.FileTypeFilter.Add(".quizxml");
                   
                    
                    storage = await openPicker.PickSingleFileAsync();

                    if (null != storage)
                    {
                        // Application now has read/write access to the picked file
                        fileName = storage.Name;
                        filePath = storage.Path;
                        loadData(quizList);
                        //questions.Text = fileName + " Click Load if this is the correct File";

                    }
                    else
                    {
                        questions.Text = "File was not returned";
                    }
                }


            }
        }

        private void last_Click(object sender, RoutedEventArgs e)
        {
            if (listCreated == true)
            {
                if (currPage == 0)
                {
                    questions.Text = "No More Questions.";
                    setImage(currPage, true);
                }

                
                else if (currPage <= quizList.Count - 1 && currPage > -1)
                {
                    currPage--;
                    //questions.Text = quizList[currPage].question.ToString();
                    questions.Text = quizList[currPage].question.ToString() + Environment.NewLine + "A: " + quizList[currPage].answerA + Environment.NewLine + "B: " +
                        quizList[currPage].answerB + Environment.NewLine + "C: " + quizList[currPage].answerC +
                        Environment.NewLine + "D: " + quizList[currPage].answerD;
                    setImage(currPage, false);
                    //answer.Text = "";
                }

                else 
                {
                    //questions.Text = quizList[0].question.ToString();
                    questions.Text = quizList[currPage].question.ToString() + Environment.NewLine + "A: " + quizList[currPage].answerA + Environment.NewLine + "B: " +
                        quizList[currPage].answerB + Environment.NewLine + "C: " + quizList[currPage].answerC +
                        Environment.NewLine + "D: " + quizList[currPage].answerD;
                    setImage(currPage,false);
                    //answer.Text = "";
                }
            }
            else
            {
                errorBox.Text = "Please load a Quiz.";
            }





        }

        private void next_Click(object sender, RoutedEventArgs e)
        {
            next_question();
        }

        private void check_Click(object sender, RoutedEventArgs e)
        {
           

            if (listCreated == true )
            {
                string temp = answer.SelectedItem.ToString();

                if (temp.Equals(quizList[currPage].answer.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {

                    scoreCount++;
                    reviewBut.Content = scoreCount + " of " + quizList.Count();
                    errorBox.Text = "Thats right!";
                    next_question();
                }
                else
                {
                    reviewClass revMe = new reviewClass();
                    getActual(quizList[currPage].answer, temp);

                    revMe.actualAnswer = actualAnswerText;
                    revMe.origQuestion = quizList[currPage].question.ToString();
                    revMe.yourAnswer = userAnswerText;
                    revMe.picture = quizList[currPage].picture;

                   App.reviewList.Add(revMe);

                   reviewBut.Content = scoreCount + " of " + quizList.Count();
                    errorBox.Text = "That is incorrect.";
                    next_question();
                }
            }
            else
            {
                errorBox.Text = "Please load a Quiz.";
            }

        }

        private void Grid_Loaded_1(object sender, RoutedEventArgs e)
        {
            ////Storyboard sb = this.FindName("quizMeStory") as Storyboard;
            //if (sb != null)
            //{
            //    sb.Begin();
            //}
        }

        private void next_question()
        {
            if (listCreated == true)
            {
                if (currPage < quizList.Count - 1)
                {
                    currPage++;
                    //questions.Text = quizList[currPage].question.ToString();
                    questions.Text = quizList[currPage].question.ToString() + Environment.NewLine + "A: " + quizList[currPage].answerA + Environment.NewLine + "B: " +
                        quizList[currPage].answerB + Environment.NewLine + "C: " + quizList[currPage].answerC +
                        Environment.NewLine + "D: " + quizList[currPage].answerD;
                    setImage(currPage, false);
                    //answer.Text = "";
                }
                else
                {
                    questions.Text = "No More Questions";
                    setImage(currPage, true);
                }
            }
            else
            {
                errorBox.Text = "Please Select a Quiz.";
            }
        }

        private void reviewBut_Click(object sender, RoutedEventArgs e)
        {
            if (App.reviewList.Count != 0)
            {
                this.Frame.Navigate(typeof(Review1));
            }
            else
            {
                errorBox.Text = "This button is used for review, you must go through a quiz first.";
            }
        }
        private void getActual(string answer, string userAnswer)
        {

            switch (answer.ToLowerInvariant())
            {
                case "a":
                    actualAnswerText = quizList[currPage].answerA;
                    break;
                case "b":
                    actualAnswerText = quizList[currPage].answerB;
                    break;
                case "c":
                    actualAnswerText = quizList[currPage].answerC;
                    break;
                case "d":
                    actualAnswerText = quizList[currPage].answerD;
                    break;
            }

            switch (userAnswer.ToLowerInvariant())
            {
                case "a":
                    userAnswerText = quizList[currPage].answerA;
                    break;
                case "b":
                    userAnswerText = quizList[currPage].answerB;
                    break;
                case "c":
                    userAnswerText = quizList[currPage].answerC;
                    break;
                case "d":
                    userAnswerText = quizList[currPage].answerD;
                    break;
            }
        }

        async private void setImage(int image,bool end)
        {
            byte[] tmp = quizList[image].picture;
            byte[] blank = new byte[1];

     
                BitmapImage tmpImg = new BitmapImage();

                var stream = new InMemoryRandomAccessStream();

                using (var writer = new DataWriter(stream))
                {
                    if (end == false)
                    {
                    writer.WriteBytes(tmp);
                    await writer.StoreAsync();
                    writer.DetachStream();
                    }
                    else
                    {
                    writer.WriteBytes(blank);
                    await writer.StoreAsync();
                    writer.DetachStream();
                    }
                }
                stream.Seek(0);
                tmpImg.SetSource(stream);

                quizImage.Source = tmpImg;
            }
        
    }
}
